import { DeliveryRecord } from '@/types';

// 导出投递记录为CSV格式
export function exportRecordsToCSV(records: DeliveryRecord[]): void {
  if (records.length === 0) {
    alert('没有可导出的投递记录');
    return;
  }

  // CSV头部
  const headers = [
    '投递时间',
    '职位名称', 
    '公司名称',
    '薪资范围',
    '所在城市',
    '详情页地址',
    '投递状态'
  ];

  // 转换数据为CSV格式
  const csvContent = [
    headers.join(','),
    ...records.map(record => [
      `"${record.deliveryTime}"`,
      `"${record.jobTitle}"`,
      `"${record.companyName}"`,
      `"${record.salary}"`,
      `"${record.location}"`,
      `"${record.detailUrl}"`,
      `"${getStatusText(record.status)}"`
    ].join(','))
  ].join('\n');

  // 添加BOM以支持中文
  const BOM = '\uFEFF';
  const blob = new Blob([BOM + csvContent], { 
    type: 'text/csv;charset=utf-8;' 
  });

  // 创建下载链接
  const link = document.createElement('a');
  const url = URL.createObjectURL(blob);
  link.setAttribute('href', url);
  
  // 生成文件名
  const now = new Date();
  const dateStr = now.toISOString().split('T')[0];
  link.setAttribute('download', `Boss直聘投递记录_${dateStr}.csv`);
  
  // 触发下载
  link.style.visibility = 'hidden';
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
  
  // 清理URL对象
  URL.revokeObjectURL(url);
}

// 获取状态文本
function getStatusText(status: string): string {
  switch (status) {
    case 'success':
      return '投递成功';
    case 'failed':
      return '投递失败';
    case 'pending':
      return '投递中';
    default:
      return '未知状态';
  }
}

// 过滤记录按日期范围
export function filterRecordsByDateRange(
  records: DeliveryRecord[],
  startDate: string,
  endDate: string
): DeliveryRecord[] {
  const start = new Date(startDate);
  const end = new Date(endDate);
  end.setHours(23, 59, 59, 999); // 包含结束日期的全天
  
  return records.filter(record => {
    const recordDate = new Date(record.deliveryTime);
    return recordDate >= start && recordDate <= end;
  });
}

// 按状态过滤记录
export function filterRecordsByStatus(
  records: DeliveryRecord[],
  status: string
): DeliveryRecord[] {
  if (status === 'all') return records;
  return records.filter(record => record.status === status);
}